<template>
  <div class="Learning-index">
    <h3>使用 <code>useMutationObserver</code> 监听dom的改变</h3>
    <codeContainer>
      <template #default>
        <div class="flex v h my-2">
          <p>改变下方盒子的背景颜色</p>
          <button @click="changeBackgroundColor">changeBackgroundColor()</button>
        </div>
        <div class="flex v h my-2">
          <p>改变下方盒子的data-number属性</p>
          <button @click="changeAttributes">changeAttributes()</button>
        </div>
        <div class="flex v h my-2">
          <p>为下方盒子添加子元素</p>
          <button @click="addChildren">addChildren()</button>
          <p>删除子元素</p>
          <button @click="removeChildren">removeChildren()</button>
        </div>
        <div class="flex v h">
          <div ref="el" :data-number="number" class="Learning-area flex col v h difference border transitionBg"
               :style="style">
            <p v-for="(item, index) in children" :key="index">{{ item }}</p>
          </div>
        </div>
        <div v-for="(text, index) of messages" :key="index">
          <p v-if='text.attributeName'>发生变化的 Attribute: {{ text.attributeName }}</p>
          <p v-if='text.addedNodes.length'>添加了子元素</p>
          <p v-if='text.removedNodes.length'>删除了子元素</p>
        </div>
      </template>
      <template #code>
            <pre data-type="js">
              {{ codeFragment["vueUse-useMutationObserver-1"] }}
            </pre>
      </template>
    </codeContainer>
    <h3>实现 <code>useEventListener</code></h3>
    <div class="code-source-wrapper" v-highlight>
      <pre data-type="js">
        {{ codeFragment["vueUse-useMutationObserver-2"] }}
      </pre>
    </div>
  </div>
</template>

<script setup>

import CodeContainer from '@/components/codeContainer/codeContainer.vue';
import { ref } from 'vue';
import { useMutationObserver } from '@/assets/js/hooks/useMutationObserver';
import codeFragment from '../../assets/js/codeFragment';
// codeFragment-split
const el = ref(null);
const number = ref(0);
const messages = ref([]);
const children = ref([ 'LEARNING' ]);

function addChildren() {
  children.value.push('LEARNING');
}

function removeChildren() {
  children.value.pop();
}

const style = ref({
  backgroundColor: '#fff'
});

function changeBackgroundColor() {
  const { backgroundColor } = style.value;
  style.value.backgroundColor = backgroundColor === '#fff' ? '#000' : '#fff';
}

function changeAttributes() {
  number.value++;
}

// 为el添加 MutationObserver 监听 dom元素的变化
useMutationObserver(
  el,
  (mutations) => {
    const mutation = mutations[0];
    console.log(mutation);
    if (!mutation) return;
    messages.value.push(mutation);
  },
  // 监听 attribute 和子元素的变化
  { attributes: true, childList: true }
);
</script>
